package com.library.library.controller;

import com.library.library.common.ServerResponse;
import com.library.library.entity.User;
import com.library.library.model.Identity.KeepIdentityService;
import com.library.library.service.UserService;
import com.library.library.util.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Auther: 杜習田
 * @Date: 2020/2/27 10:02
 * @Description:
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private KeepIdentityService<User> keepIdentityService;

    @PostMapping("register")
    private ServerResponse register(User user){
        if (userService.findByUsername(user.getUsername()) != null){
            return ServerResponse.createByErrorMessage("用户名已存在！");
        }
        user.setPassword(EncryptUtils.getMd5UseApacheCodec(user.getPassword()));
        userService.save(user);
        log.info(String.format("用户 %s 注册成功！",user.getUsername()));
        return ServerResponse.createBySuccessMessage("注册成功！");
    }

    @PostMapping("login")
    private ServerResponse login(User user,String code, HttpServletRequest request){
        HttpSession session = request.getSession();
        if(StringUtils.isBlank(code)){
            return ServerResponse.createByErrorMessage("验证码为空！");
        }
        if(!code.equals(session.getAttribute("validationCode"))){
            return ServerResponse.createByErrorMessage("验证码错误！");
        }

        User user1 = userService.findByUsername(user.getUsername());
        if(user1 == null){
            return ServerResponse.createByErrorMessage("用户名不存在！");
        }
        if(!user1.getPassword().equals(EncryptUtils.getMd5UseApacheCodec(user.getPassword()))){
            return ServerResponse.createByErrorMessage("密码错误！");
        }
        log.info(String.format("用户 %s 登录成功！",user.getUsername()));
        keepIdentityService.setIdentity("user",user1,request);
        return ServerResponse.createBySuccessMessage("登陆成功！");
    }
    @GetMapping("loginOut")
    private ServerResponse loginOut(HttpServletRequest request){
        User user = keepIdentityService.delIdentity("user",request);
        log.info(String.format("用户 %s 登出成功！",user.getUsername()));
        return ServerResponse.createBySuccessMessage("登出成功！");
    }
}
